#!/usr/bin/env python
# encoding: utf-8
"""
poco_public.py

Created by Bud Gibson on 2010-05-29.
Copyright (c) Bud Gibson 2010. Released under the Artistic/GPL License.
"""

from fetchers import fetch_buzz_data, fetch_buzz_loop
try:
  import simplejson as json
except ImportError:
  import json

endpoint = '/people/'

def json_decode(content):
  """If necessary removes hidden control characters from json content and decodes it"""
  try:
    jsonData = json.loads(content)
  except json.decoder.JSONDecodeError:
    print 'now trying JSON decoder with strict set to false'
    laxDecode = json.JSONDecoder(strict=False)
    jsonData = laxDecode.decode(content)
  return jsonData

def __subset_profile(fullProfile):
  """Get a subset of the portable contact information sent back by buzz"""
  poco_subset = {}
  dataEls = ['id', 'displayName', 'profileUrl', 'thumbnailUrl']
  for el in dataEls:
    try:
      poco_subset[el] = fullProfile[el].encode('ascii', 'xmlcharrefreplace')
    except KeyError:
      pass
  return poco_subset

def poco_json(content):
  """Gets the returned json from the poco end point so it can be passed
    around
  """
  jsonData = json_decode(content)
  try:
    return jsonData['data']['entry']
  except KeyError:
    return jsonData['data']

def poco_json_loop(content):
  """Gets the control data for looping through paged results"""
  data = {}
  jsonData = json_decode(content)
  data['totalResults'] = jsonData['data']['totalResults']
  data['startIndex'] = jsonData['data']['startIndex']
  try:
    data['entry'] = jsonData['data']['entry']
  except KeyError:
    data['entry'] = []
  return data

#Create the coroutine object for fetching poco from buzz
fetch_buzz_poco = fetch_buzz_data(poco_json)

#Create the coroutine object for fetching poco lists from buzz
fetch_poco_list = fetch_buzz_loop(poco_json_loop,__subset_profile)

def profile_stub(personId):
  """Gets the necessary poco subset for a person"""
  call = endpoint + personId + '/@self?alt=json'
  return __subset_profile(fetch_buzz_poco.send(call))
  
def followers_of(personId):
  """fetches a person's followers"""
  call = endpoint + personId + '/@groups/@followers?alt=json'
  global fetch_poco_list 
  try:
    return fetch_poco_list.send(call)
  except StopIteration:
    fetch_poco_list = fetch_buzz_loop(poco_json_loop,__subset_profile)
    return fetch_poco_list.send(call)

def followed_by(personId):
  """fetches those who a person follows"""
  call = endpoint + personId + '/@groups/@following?alt=json'
  global fetch_poco_list
  try:
    return fetch_poco_list.send(call)
  except StopIteration:
    fetch_poco_list = fetch_buzz_loop(poco_json_loop,__subset_profile)
    return fetch_poco_list.send(call)

def list_profile_stubs(people):
  """Gets profiles for a list of people"""
  profile_stubs = [profile_stub(person) for person in people]
  return profile_stubs

def main():
  import pprint
  pp = pprint.PrettyPrinter(depth=2)
  people = [
    'chris.prucha','adewale',
    ]
  print '-' * 80
  print 'profile_stub(personId)'
  print '-' * 80
  pp.pprint(profile_stub('fpgibson'))
  print '-' * 80
  print 'followed_by(personId)'
  print '-' * 80
  fb =  followed_by('fpgibson')
  print 'number following =', len(fb)
  #pp.pprint(fb)
  print '-' * 80
  print 'followers_of(personId)'
  print '-' * 80 
  fo = followers_of('fpgibson')
  print 'number of followers =', len(fo)
  #pp.pprint(fo)
  print '-' * 80
  print 'list_profile_stubs(people)'
  print '-' * 80
  pp.pprint(list_profile_stubs(people)) 
  

if __name__ == '__main__':
  main()

